package com.yiguo.common;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.R.integer;
import android.content.Context;
import android.os.AsyncTask;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.widget.TextView;

public class LoaderGPRSLocation extends AsyncTask<Void, Void, Void>
{
   public LoaderGPRSLocation(Context context,Dialogs _dialogs,TextView _textView)
   {
	  tm=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
      dialogs=_dialogs;
      textView=_textView;
   }
   
   TelephonyManager tm;
   Dialogs dialogs;
   String address="";;
   TextView textView;
   int[] cids;
   int[] lacs;
   void getStation()
   {
	  GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
	  int cid = gcl.getCid();
	  int lac = gcl.getLac();

	  int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
	  int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
	 
      List<NeighboringCellInfo> infos=tm.getNeighboringCellInfo();
      for(NeighboringCellInfo info:infos){
          //获取邻居小区号
          int cid2=info.getCid();
          //获取邻居小区LAC，LAC: 位置区域码。为了确定移动台的位置，每个GSM/PLMN的覆盖区都被划分成许多位置区，LAC则用于标识不同的位置区。
          info.getLac();
          info.getNetworkType();
          info.getPsc();
          //获取邻居小区信号强度  
          info.getRssi();
      }
	  
	  try
	  {
		 // 组装JSON查询字符串
		 JSONObject holder = new JSONObject();
		 holder.put("version", "1.1.0");
		 holder.put("host", "maps.google.com");
		 // holder.put("address_language", "zh_CN");
		 holder.put("request_address", true);

		 JSONArray array = new JSONArray();
		 JSONObject data = new JSONObject();
		 data.put("cell_id", cid); // 25070
		 data.put("location_area_code", lac);// 4474
		 data.put("mobile_country_code", mcc);// 460
		 data.put("mobile_network_code", mnc);// 0
		 array.put(data);
		 holder.put("cell_towers", array);

		 // 创建连接，发送请求并接受回应
		 DefaultHttpClient client = new DefaultHttpClient();

		 HttpPost post = new HttpPost("http://www.google.com/loc/json");

		 StringEntity se = new StringEntity(holder.toString());

		 post.setEntity(se);
		 HttpResponse resp = client.execute(post);

		 HttpEntity entity = resp.getEntity();

		 BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
		 StringBuffer sb = new StringBuffer();
		 String result = br.readLine();

		 while (result != null)
		 {
			sb.append(result);
			result = br.readLine();
		 }
		 JSONObject jsonObject = new JSONObject(sb.toString());

		 JSONObject jsonObject1 = new JSONObject(jsonObject.getString("location"));

		 getAddress(jsonObject1.getString("latitude"), jsonObject1.getString("longitude"));


	  }
	  catch (Exception e)
	  {
		 // TODO: handle exception
	  }

   }
   
   void getAddress(String lat, String lag)
   {
	  try
	  {
		 URL url = new URL("http://maps.google.cn/maps/geo?key=abcdefg&q=" + lat + "," + lag);
		 InputStream inputStream = url.openConnection().getInputStream();
		 InputStreamReader inputReader = new InputStreamReader(inputStream, "utf-8");
		 BufferedReader bufReader = new BufferedReader(inputReader);

		 String line = "", lines = "";

		 while ((line = bufReader.readLine()) != null)
		 {
			lines += line;
		 }
		 if (!lines.equals(""))
		 {
			JSONObject jsonobject = new JSONObject(lines);
			JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark").toString());
			for (int i = 0; i < jsonArray.length(); i++)
			{
			   address= address + jsonArray.getJSONObject(i).getString("address");
			}
		 }
	  }
	  catch (Exception e)
	  {
        e.printStackTrace();
	  }
   }

   @Override
   protected void onPreExecute()
   {
	  // TODO Auto-generated method stub
     dialogs.ShowLoadingDialogNoTitle("获取位置中...", null);
   }

   @Override
   protected Void doInBackground(Void... params)
   {
	  // TODO Auto-generated method stub
	  getStation();
	  return null;
   }

   @Override
   protected void onPostExecute(Void result)
   {
	  // TODO Auto-generated method stub
	  dialogs.setDialogDismiss();
      textView.setText(address);
   }
}
